<template>
  <div class="common-layout">
    <Header/>
    <el-container id="container">
      <el-main>
        <div id="moviePicAndDesp">
          <el-image :src="imgPrefix+movieDetail.mPic" fit="scale-down"/>
          <el-form v-model="movieDetail" size="large">
            <el-form-item label="电影名称">
              <el-text tag="b">{{ movieDetail.mName }}</el-text>
            </el-form-item>
            <el-form-item label="电影外名">
              <el-text tag="b">{{ movieDetail.fgName }}</el-text>
            </el-form-item>
            <el-form-item label="时长">
              <el-text tag="b">{{ movieDetail.mDuration }}</el-text>
            </el-form-item>
            <el-form-item label="上映时间">
              <el-text tag="b">{{ movieDetail.releaseAt }}</el-text>
            </el-form-item>
            <el-form-item label="电影类型">
              <el-text>
                <el-tag size="small" tag="b">{{ movieDetail.mtName }}</el-tag>
              </el-text>
            </el-form-item>
            <el-form-item label="电影介绍">
              <el-text tag="b" style="text-align: left">
                {{ movieDetail.mDetail }}
              </el-text>
            </el-form-item>
            <el-form-item label="电影平均评分">
              <el-rate
                  v-model="movieDetail.avgMovieScore"
                  disabled
                  show-score
                  :icons="icons"
                  :void-icon="StarFilled"
                  :colors="['#000000', '#136add', '#ff0019']"/>
            </el-form-item>
            <el-form-item>
              <div id="dialogFooterButton">
                <el-button @click="backHome" size="large">关闭</el-button>
                <el-button type="primary" @click="toBuyTicket" size="large">去购票</el-button>
              </div>
            </el-form-item>
          </el-form>

        </div>
        <div id="actorShow">
          <div id="actorText" style="display: flex">
            <el-text style="font-size: 20px;margin-top: 100px;margin-left:100px">
              <b>演职人员</b></el-text>
          </div>
          <div id="actorList">
            <el-card style="max-width: 200px;"
                     shadow="always"
                     v-for="movieActor in movieDetail.movieActorVoList">
              <template #header>
                <span v-if="movieActor.isDirector==='0'">导演</span>
                <span v-else-if="movieActor.isDirector==='1'">演员</span>
              </template>
              <el-image
                  :src="imgPrefix+movieActor.aPic"
              />
              <template #footer>
                <span style="color: #2b76b9">{{ movieActor.aName }}</span>
                <span style="color: #b00b0b" v-if="movieActor.isDirector==='1'"> 扮演  {{ movieActor.mRole }}</span>
              </template>
            </el-card>
          </div>
        </div>
        <div style="margin:0 auto;">
          <div style="display: flex;align-items: flex-end;">
            <el-text style="font-size: 20px;margin-top: 100px;margin-left:100px">
              <b>电影评论</b></el-text>
            <el-radio-group v-model="commentSort" size="small" @change="changeCondition" style="margin-left:800px">
              <el-radio-button value="0">按评论时间排序</el-radio-button>
              <el-radio-button value="1">按打分排序</el-radio-button>
            </el-radio-group>
          </div>

          <div id="oneComment" v-for="comment in commentCurrentPageData">
            <div id="commentUser">
              <el-avatar shape="square" :size="60" fit="cover" :src="imgPrefix+comment.uPic" alt="头像异常"/>
              <el-text>{{ comment.displayName }}</el-text>
            </div>
            <div id="commentInfo">
              <div id="commentOtherInfo">
                <el-rate
                    v-model="comment.commentScore"
                    disabled
                    :icons="icons"
                    :void-icon="StarFilled"
                    :colors="['#000000', '#136add', '#ff0019']"/>
                <el-text>{{ comment.commentAt }}</el-text>
              </div>
              <div id="commentText">
                <el-text>{{ comment.commentContent }}</el-text>
              </div>
            </div>
          </div>
          <div id="toCommentDiv">

            <el-input
                type="textarea"
                v-model="commentContent"
                style="width: 57%;margin-top:20px;margin-left: 100px;"
                placeholder="我也来说两句"
                size="large"
            />
            <el-rate
                size="large"
                style="float: left;"
                v-model="rateScore"
                :icons="icons2"
                :void-icon="ChatRound"
                :colors="['#000000', '#136add', '#ff0019']"
            />
            <el-button type="primary" plain size="large" @click="insertComment">
              发表评论
            </el-button>
          </div>
        </div>
      </el-main>
      <el-footer>
        <div id="commentPage">
          <el-pagination
              style="float:right"
              v-model:page-size="commentPageSize"
              :page-sizes="[5, 10, 20, 40]"
              :current-page="commentCurrentPage"
              :disabled="false"
              :total="commentTotalCount"
              @current-change="commentHandleCurrentChange"
              @size-change="commentHandleSizeChange"
              background layout="total, sizes, prev, pager, next, jumper"/>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>
<script setup>
import {ElNotification} from "element-plus";
import request from "../../../request.js";
import {request2} from "@/request.js";
import qs from 'qs'
import {ref, reactive, inject} from "vue";
import {Search, StarFilled, ChatRound, ChatLineRound, ChatDotRound} from '@element-plus/icons-vue'
import SessionStorage from "@/SessionStorage.js";
import axios from "axios";
import moment from 'moment'
import Header from "@/components/Header.vue";
import {useRoute} from "vue-router";
import {useRouter} from "vue-router"

const baseIp = import.meta.env.VITE_APP_API_URL;

const route = useRoute();
const router = useRouter();

const midWith = route.params.mid;
console.log("从首页跳转之后，携带的mid为：" + midWith);
const loginUser = SessionStorage.getItem("loginUser");
const imgPrefix = inject('imgPrefix');
// 电影详情
const icons = [StarFilled, StarFilled, StarFilled]
const icons2 = [ChatRound, ChatLineRound, ChatDotRound];
const movieDetail = reactive({
  mid: -1,
  mtId: -1,
  mtName: "",
  releaseAt: "",
  mName: "",
  mDetail: "",
  fgName: "",
  mDuration: "",
  mPic: "",
  avgMovieScore: 0.0,
  movieActorVoList: [{
    aid: -1,
    aName: "",
    aPic: "",
    mRole: "",
    isDirector: ""
  }]
})
const showMovieDetail = (mid) => {
  const midObject = reactive({
    mid: ""
  })
  midObject.mid = mid;
  axios.post(
      baseIp + ":9090/movie/getByMid",
      qs.stringify(midObject),
      {headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}}
  ).then(res => {
    if ('200' === res.data.code && res.data.data != null) {
      console.log('根据mid查询电影成功！');
      console.log('查看电影详情接口返回的数据：', res.data);
      const movieDetailBack = res.data.data;
      movieDetail.mid = movieDetailBack.id;
      movieDetail.avgMovieScore = movieDetailBack.avgMovieScore;
      movieDetail.mtId = movieDetailBack.mtId;
      movieDetail.mtName = movieDetailBack.mtName;
      movieDetail.releaseAt = new Date(movieDetailBack.releaseAt).toLocaleDateString();
      movieDetail.mName = movieDetailBack.mName;
      movieDetail.mDetail = movieDetailBack.mDetail;
      movieDetail.fgName = movieDetailBack.fgName;
      movieDetail.mDuration = movieDetailBack.mDuration + "分钟";
      movieDetail.mPic = movieDetailBack.mPic;
      movieDetail.movieActorVoList.splice(0, movieDetail.movieActorVoList.length);
      movieDetailBack.movieActorVoList.forEach((item) => {
        movieDetail.movieActorVoList.push(item);
      });
    } else {
      console.log('查询电影详情失败！');
      ElNotification({
        type: 'error',
        message: res.msg
      })
    }
  })
}
showMovieDetail(midWith);

const toBuyTicket = () => {
  console.log("查看电影详情的id：" + midWith);
  router.push({name: "SelectOrganize", params: {mid: midWith}});
}

const backHome = () => {
  router.push("/home");
}
// 电影评论
// 排序
const commentSort = ref('0')
const changeCondition = (val) => {
  console.log('评论排序的单选值发生了改变，当前选中的值为：', val);
  commentSort.value = val;
  showComment(midWith, commentSort);
}
// 分页变量
const commentCurrentPage = ref(1);
const commentPageSize = ref(5);
const commentTotalCount = ref(0);
// 用于存储当前页的数据
const commentCurrentPageData = reactive([]);

const movieCommentQuery = reactive({
  mid: -1,
  orderByCondition: "0",
  pageNo: 1,
  pageSize: 5
})
const showComment = (mid, orderByCondition) => {
  // 打开对话框
  const commentMid = mid;
  console.log("评论电影的mid：" + commentMid);
  console.log("电影评论的排序规则：" + orderByCondition);
  movieCommentQuery.mid = commentMid;
  movieCommentQuery.orderByCondition = orderByCondition;
  request({
    url: "/movie/getCommentByMid",
    method: "post",
    data: movieCommentQuery
  }).then(res => {
    if ('200' === res.code && res.data != null) {
      console.log('查询评论成功！');
      console.log('接口返回的数据详情：', res.data);
      if (res.data && Array.isArray(res.data.list) && typeof res.data.totalCount === 'number') {
        // 清空原有数据
        commentCurrentPageData.splice(0, commentCurrentPageData.length);
        // 更新总数据量
        commentTotalCount.value = res.data.totalCount;
        // 更新当前页数据
        const queryList = res.data.list;
        queryList.forEach((item) => {
          item.commentAt = moment(item.commentAt).format("YYYY-MM-DD HH:ss:mm");
          commentCurrentPageData.push(item);
        });
      } else {
        console.log('返回格式参数错误！');
        ElNotification({
          type: 'error',
          message: "返回格式参数错误！"
        })
      }
    } else {
      console.log('查询评论失败！');
      ElNotification({
        type: 'error',
        message: res.msg
      })
    }

  })
}
showComment(midWith, commentSort);
// 处理当前页码改变的方法
const commentHandleCurrentChange = async (newPage) => {
  console.log("pageNo修改为第" + newPage + "页！");
  commentCurrentPage.value = newPage;
  // 重新构建movieCommentQuery
  movieCommentQuery.pageNo = commentCurrentPage.value;
  movieCommentQuery.pageSize = commentPageSize.value;
  showComment(midWith, commentSort);
};

// 处理每页显示数量改变的方法
const commentHandleSizeChange = async (newSize) => {
  console.log("pageSize修改为每页" + newSize + "条！");
  commentPageSize.value = newSize;
  commentCurrentPage.value = 1;
  // 重新构建movieCommentQuery
  movieCommentQuery.pageNo = commentCurrentPage.value;
  movieCommentQuery.pageSize = commentPageSize.value;
  showComment(midWith, commentSort);
};

const rateScore = ref(0);
const commentContent = ref("");

const insertComment = () => {
  if (rateScore.value === null || commentContent.value === null || commentContent.value.trim() === "") {
    ElNotification.error("评论内容和打分都不能为空！")
    return;
  }
  const createDto = reactive({
    uid: loginUser.uid,
    mid: midWith,
    commentContent: commentContent.value,
    commentScore: rateScore.value
  })


  request2({
    url: "/comment/insert",
    method: "post",
    data: createDto
  }).then(res => {
    if ('200' === res.code) {
      console.log('创建评论成功！');
      rateScore.value = 0;
      commentContent.value = ""
      showComment(midWith, commentSort);
      ElNotification.success(res.msg);
    } else {
      ElNotification.error(res.msg)
    }
  })
}
</script>
<style scoped>
#container {
  margin: auto 0;
}

.el-main {
  display: flex;
  flex-direction: column;
  margin: 0 auto;
}

#actorList {
  margin-left: 80px;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-content: space-around;
}

#actorList .el-card {
  margin: 40px 20px;

}

#moviePicAndDesp {
  display: flex;
  margin: 10px auto;
}


#moviePicAndDesp .el-image {
  margin-left: 100px;
  margin-right: 50px;
}

#moviePicAndDesp .el-form {
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin: 0 auto;
  width: 500px;
}

#actorShow {
  margin: 0 auto;
}

#oneComment {
  display: flex;
  margin-left: 100px;
  margin-top: 20px;
}

#commentUser {
  display: flex;
  flex-direction: column;
  margin-top: 22px;
}

#commentText {
  width: 1000px;
  margin-left: 20px;
  border: 2px solid gray;
  border-radius: 10px;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-content: space-around;
}

#commentText .el-text {
  padding: 20px 20px;
}

#commentOtherInfo {
  display: flex;
}

#commentOtherInfo .el-rate {
  margin-left: 20px;
}

#commentOtherInfo .el-text {
  margin-left: 20px;
}

#toCommentDiv {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-start;

  .el-rate {
    margin-left: 100px;
  }

  .el-button {
    margin-left: 1100px;
  }

}

</style>
